package com.boot.down.util;

import com.boot.down.service.UserInfoService;
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
public class JwtUtil {

    private static UserInfoService userInfoService;
    @Autowired
    public JwtUtil(UserInfoService userInfoService) {
        JwtUtil.userInfoService = userInfoService;
    }

    /*默认有效时间*/
    private static final long EXPIRATION_TIME = 3600000000L;
    static final String SECRET = "Jwt_learn";
    static final String TOKEN_PREFIX = "Bearer";
    static final String HEADER_STRING = "Authorization";

    public static String getToken(String userName, Date lastLoginTime){
        HashMap<String, Object> map = Maps.newHashMap();

        map.put("username", userName);
        map.put("lastLoginTime",lastLoginTime);

        String jwt = Jwts.builder().setClaims(map)
                .setExpiration(new Date(lastLoginTime.getTime() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return jwt;
    }

    public static Map<String, Object> validataToken(String token){
        Assert.hasText(token,"token 不能为空");

        Map<String, Object> map = Maps.newHashMap();
        if(StringUtils.isNotEmpty(token)) {
            try {
                Map<String, Object> userMap = Jwts.parser().setSigningKey(SECRET)
                        .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                        .getBody();
                String username = (String) userMap.get("username");
                Date lastLoginTime = new Date((Long)userMap.get("lastLoginTime"));
                if (StringUtils.isEmpty(username)) {
                    map.put("error_msg", "用户名不能为空");
                    return map;
                }
                //怎么证明该账号在别处登录

                map.put("username", username);
                map.put("lastLoginTime", lastLoginTime);
                return map;
            } catch (SignatureException | MalformedJwtException ex) {
                map.put("error_msg", "token解析错误");
                return map;
            } catch (ExpiredJwtException e) {
                map.put("error_msg", "token已经过期");
                return map;
            }
        } else{
            map.put("error_msg", "token不能为空");
            return map;
        }


    }

}
